<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
    public function __construct()
    {
        $this->middleware('guest', ['only' => ['getLogin', 'getRegister']]);
    }

    public function getLogin()
    {
        return view('auth.login');
    }

    public function getRegister()
    {
        return view('auth.register');
    }

    public function postRegister(Request $request)
    {
        $date      = $request->all();
        $validator = Validator::make($date, [
            'username' => 'required|unique:users',
            'password' => 'required|confirmed',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $date['password'] = password_hash($date['password'], PASSWORD_BCRYPT);
        $user             = User::create($date);

        Auth::login($user);

        return redirect()->route('user-me');
    }

    public function postLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required|exists:users',
            'password' => 'required',
        ], [
            'username.exists' => 'User not exists',
        ]);
        $username  = trim($request->get('username'));
        $password  = trim($request->get('password'));
        if (Auth::attempt(['username' => $username, 'password' => $password])) {
            $user = User::where('username', $username)->first();
            Auth::login($user);

            return redirect()->route('user-me');
        }

        return redirect()->back()->withErrors($validator)->withInput();
    }

    public function logout()
    {
        Auth::logout();

        return redirect()->route('home');
    }
}
